<?php


namespace app\services;


use app\models\Baseinfo;

class BaseinfoService {
    public static function getPageList($student, $page, $limit) {
        $where = [];
        if($student != '') {
            $where[] = ['student', 'like', '%'.$student.'%'];
        }
        $res = Baseinfo::getPageList($where, $page, $limit);
        return $res;
    }

    public static function createData($student, $password, $uuid, $serial, $classes, $phone, $address, $guardian, $status, $note) {
        $baseinfoInfo = Baseinfo::getInfo(['student' => $student]);
        if($baseinfoInfo) {
            throwError('账号已存在');
        }
        $sign = generateSign(7);
        $password = md5($password.$sign);
        Baseinfo::create([
            'student' => $student,
            'password' => $password,
            'sign' => $sign,
            'uuid' => $uuid,
            'serial' => $serial,
            'classes' => $classes,
            'phone' => $phone,
            'address' => $address,
            'guardian' => $guardian,
            'status' => $status,
            'note' => $note,
            'create_time' => time()
        ]);
        return 1;
    }

    public static function updateData($id, $student, $password, $uuid, $serial, $classes, $phone, $address, $guardian, $status, $note) {
        $baseinfoInfo = Baseinfo::getInfoById($id);
        if(!$baseinfoInfo) {
            throwError('用户不存在');
        }
        if($baseinfoInfo['student'] != $student) {
            $count = Baseinfo::getCount(['student' => $student]);
            if($count) {
                throwError('用户已存在');
            }
        }
        $data = [
            'student' => $student,
            'uuid' => $uuid,
            'serial' => $serial,
            'classes' => $classes,
            'phone' => $phone,
            'address' => $address,
            'guardian' => $guardian,
            'status' => $status,
            'note' => $note,
        ];
        if($password) {
            $sign = generateSign(7);
            $password = md5($password.$sign);
            $data['sign'] = $sign;
            $data['password'] = $password;
        }
        Baseinfo::update($data, ['id' => $id]);
        return 1;
    }

    public static function deleteData($id) {
        $baseinfoInfo = Baseinfo::getInfoById($id);
        if(!$baseinfoInfo) {
            throwError('用户不存在');
        }
        return Baseinfo::where('id', '=', $id)->delete();
    }
}